package com.aboxes.sqlite.util;

import java.util.HashMap;
import java.util.Map;

import android.database.Cursor;

@SuppressWarnings("unchecked")
public class CursorValueUtil {
	public static Object getValue(Cursor cursor, String columnName, Class fieldType) {
		GetCursorValue cursorValue = IMPL_MAP.get(fieldType);
		if (cursorValue != null) {
			return cursorValue.getValue(cursor, columnName);
		}

		throw new RuntimeException("andriod not be supported value type!");
	}

	private static final Map<Class, GetCursorValue> IMPL_MAP = new HashMap() {
		private static final long serialVersionUID = 1L;
		{
			put(Double.class, new GetCursorValue() {
				@Override
				public Object getValue(Cursor cursor, String columnName) {
					return cursor.getDouble(cursor.getColumnIndex(columnName));
				}
			});

			put(Float.class, new GetCursorValue() {
				@Override
				public Object getValue(Cursor cursor, String columnName) {
					return cursor.getFloat(cursor.getColumnIndex(columnName));
				}
			});

			put(Integer.class, new GetCursorValue() {
				@Override
				public Object getValue(Cursor cursor, String columnName) {
					return cursor.getInt(cursor.getColumnIndex(columnName));
				}
			});

			put(Long.class, new GetCursorValue() {
				@Override
				public Object getValue(Cursor cursor, String columnName) {
					return cursor.getLong(cursor.getColumnIndex(columnName));
				}
			});

			put(Short.class, new GetCursorValue() {
				@Override
				public Object getValue(Cursor cursor, String columnName) {
					return cursor.getShort(cursor.getColumnIndex(columnName));
				}
			});

			put(String.class, new GetCursorValue() {
				@Override
				public Object getValue(Cursor cursor, String columnName) {
					return cursor.getString(cursor.getColumnIndex(columnName));
				}
			});

			put(byte[].class, new GetCursorValue() {
				@Override
				public Object getValue(Cursor cursor, String columnName) {
					return cursor.getBlob(cursor.getColumnIndex(columnName));
				}
			});
		}
	};
}
